package com.example.hbutliving.es.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ActivityESService {

  @Autowired
  private RestHighLevelClient restHighLevelClient;

  private static String ENV;

  @Value("${spring.profiles.active}")
  public void setENV(String ENV) {
    ActivityESService.ENV = ENV;
  }

  /**
    only local env can use elasticsearch
    */
  public static boolean enable(){
    if("local".equals(ENV)){
      return true;
    }
    return false;
  }


  public void save(int id,String text){
    if(!ActivityESService.enable()){
      return;
    }
    IndexRequest indexRequest = new IndexRequest("activity");
    indexRequest.source("id",id,"text",text);
    try {
      IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
      log.info(indexResponse.toString());
    } catch (IOException e) {
      e.printStackTrace();
      log.error(e.getMessage());
    }
  }

  public ArrayList<Integer> search(String text,int page){
    SearchRequest searchRequest = new SearchRequest();
    searchRequest.indices("activity");
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.from((page-1)*5);
    searchSourceBuilder.size(5);
    searchSourceBuilder.query(QueryBuilders.matchQuery("text",text));
    searchRequest.source(searchSourceBuilder);
    ArrayList<Integer> arrayList =new ArrayList<>();
    try {
      SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
      log.info(searchResponse.toString());
      SearchHits hits = searchResponse.getHits();
      for (SearchHit hit : hits) {
        String sourceAsString = hit.getSourceAsString();
        JSONObject jsonObject = JSON.parseObject(sourceAsString);
        int id =(int) jsonObject.get("id");
        arrayList.add(id);
      }
      return arrayList;
    } catch (IOException e) {
      e.printStackTrace();
      log.error(e.getMessage());
    }
    return arrayList;
  }

}
